# coding: utf-8
"""
Request Util
"""
from datetime import datetime
import json
from uuid import uuid4
import requests

HOST = "http://112.74.172.50/k3cloud"
ACCT_ID = "59f15ca10e68be"
USERNAME = "kingdee2"
PASSWORD = "123456"


class RequestUtil:
    """
    Request Util
    """

    def __init__(self):
        self.cookies = {}
        self.headers = {
            "Content-Type": "application/json"
        }

        self.validate_user()

    def __do_request(self, path, parameters):
        data = json.dumps({
            "format": 1,
            "useragent": "ApiClient",
            "rid": str(hash(uuid4().hex)),
            "parameters": parameters,
            "timestamp": datetime.now().isoformat(),
            "v": "1.0"
        })

        response = requests.post(url=HOST + path,
                                 data=data,
                                 cookies=self.cookies,
                                 headers=self.headers)
        if response.status_code == 200:
            self.cookies.update(response.cookies)
            return json.loads(self.__validate_response(response.text))
        else:
            raise Exception(response.status_code)

    @staticmethod
    def __validate_response(response):
        if response and response.startswith("response_error:"):
            raise Exception(response)
        return response

    def validate_user(self):
        """
        validate user by username and password
        """
        login_path = "/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc"
        parameters = json.dumps([
            ACCT_ID,  # acctId
            USERNAME,  # username
            PASSWORD,  # password
            2052  # lcid
        ])
        response = self.__do_request(path=login_path, parameters=parameters)
        return int(response["LoginResultType"]) == 1

    def query(self, form_id, fields_keys,
              top_row_count=0, limit=9999, start_row=0,
              filter_string="", order_string=""):
        """
        query with parameters
        """
        query_path = "/Kingdee.BOS.WebApi.ServicesStub." + \
                     "DynamicFormService.ExecuteBillQuery.common.kdsvc"
        parameters = json.dumps([
            json.dumps({
                "FormId": form_id,
                "TopRowCount": top_row_count,
                "Limit": limit,
                "StartRow": start_row,
                "FilterString": filter_string,
                "OrderString": order_string,
                "FieldKeys": fields_keys
            })
        ])
        return self.__do_request(path=query_path, parameters=parameters)


REQUEST_UTIL = RequestUtil()


# def get_products_by_category(request_util: RequestUtil, category_id: str):
#     '''
#     get all product under category
#     '''
#     data = request_util.query("BD_MATERIAL", \
#             fields_keys="FMasterId,FNumber," + \
#                         "FName,FMaterialGroup.FName,FDescription,FBaseProperty," + \
#                         "FSpecification,FIsSale,FSaleUnitId.FName," + \
#                         "FSalePriceUnitId.FName", \
#             filter_string="FMaterialGroup=%s" % category_id)
#     return [create_product(item) for item in data]
def get_products_by_category(request_util: RequestUtil, category_id=''):
    material_fields_keys = [
        "FMasterID",
        "FName",
        "FMaterialGroup",
        "FImage1",
        "FImageFileServer",
        "FDescription",
        "FIsSale",
        "FSaleUnitID.FName"]
    data = request_util.query("BD_MATERIAL",
                              fields_keys=",".join(material_fields_keys),
                              filter_string="FMaterialGroup=%s" % category_id
                              if category_id is not None and category_id != '' else '')
    material_data = {}
    for item in data:
        material_data[item[0]] = item

    # 价格
    price_fields_keys = [
        "FMaterialId",
        "FPrice"
    ]

    # 库存
    inventory_fields_key = [
        "FMaterialId",
        "FAVBQty",  # 可用库存（主单位）
        "FQty"  # 主单位
    ]
    inventory_list = request_util.query("STK_Inventory",
                                        fields_keys=",".join(inventory_fields_key))
    inventory_list = filter(lambda x: x[0] in material_data, inventory_list)
    inventory_data = {}
    for item in inventory_list:
        inventory_data[item[0]] = item

    price_list = request_util.query("BD_SAL_PriceList",
                                    fields_keys=",".join(price_fields_keys))
    price_list = filter(lambda x: x[0] in material_data and x[0] in inventory_data, price_list)

    return [create_product(price_item, material_data, inventory_data) for price_item in price_list]


def create_product(price_item, material_data, inventory_data):
    """
    translate item to product
    """
    FMaterialId = 0
    FPrice = 1  # 价格
    FMasterID = 0
    FName = 1
    FMaterialGroup = 2
    FImage1 = 3
    FImageFileServer = 4
    FDescription = 5
    FIsSale = 6
    FUnit = 7
    FAVBQty = 1  # 库存
    material_id = price_item[FMaterialId]
    item = material_data[material_id]
    return {
        'product_id': item[FMasterID],
        'name': item[FName],
        'category_id': item[FMaterialGroup],
        'image_url': item[FImage1],
        'description': item[FDescription],
        'detail_images': [
            {
                'id': 0,
                'image_url': item[FImage1],
                'order': 0,
                'description': ''
            }
        ],
        'specs': [
            {
                'spec_id': item[FMasterID],
                'name': item[FName],
                'description': item[FDescription],
                'unit': item[FUnit],
                'price_for_display': '',
                'price': price_item[FPrice] * 100,  # 分
                'discount': '',
                'stock': inventory_data[material_id][FAVBQty],
                'image_url': item[FImage1],
                'is_on_shell': item[FIsSale],
                'deposit': '',
                'deposit_desc': ''
            }
        ]
    }


def login(request_util: RequestUtil, phone: str):
    request_util.query("BD_Consumer", fields_keys='')


# if __name__ == '__main__':
    # REQUEST_UTIL = RequestUtil()
    # print(get_all_category(REQUEST_UTIL))
    # print(get_products_by_category(REQUEST_UTIL, 100405))
    # print(REQUEST_UTIL.query("BD_SAL_PriceList", \
    #         fields_keys="FName,FMaterialId,FMaterialId.FName", filter_string=""))
